import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import {
  getWarehouseLocationListApi,
  createWarehouseLocationApi,
  updateWarehouseLocationApi,
  delWarehouseLocationApi,
  getWarehouseLocationShowApi,
  updateStatusWarehouseLocationApi
} from "@/api/warehouseApi";
export function useLocation() {
  const form = reactive({
    page: 1,
    perPage: 10,
    keyword: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const getStatusType = (type, text = false) => {
    switch (type) {
      case 1:
        return text ? "启用" : "primary";
      case 2:
        return text ? "禁用" : "danger";
    }
  };
  const switchLoadMap = ref({});
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "warehouseLocationId",
      width: 80
    },
    {
      label: "库位名称",
      prop: "name"
    },
    {
      label: "库位编码",
      prop: "code"
    },
    {
      label: "所属仓库",
      prop: "warehouse.name"
    },
	{
	  label: "所属库区",
	  prop: "warehouseArea.name"
	},
	{
	  label: "巷道号",
	  prop: "number"
	},
    {
      label: "状态",
      prop: "status",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2}
          active-text="启用"
          inactive-text="禁用"
          inline-prompt
          onChange={() => switchChange(scope as any)}
        />
      )
    },
	{
	  label: "备注",
	  prop: "remarks"
	},
    {
      label: "创建时间",
      prop: "createdAt"
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 180
    }
  ];
  function switchChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 2 ? "禁用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          updateStatusWarehouseLocationApi({
            warehouseLocationId: row.warehouseLocationId,
            status: row.status
          }).then((res) => {
  			if(res?.code === 200) {
  				message("操作成功!", {
  				  type: "success"
  				});
  				onSearch()
  			}
            
          });
        }, 300);
      })
      .catch(() => {
        row.status === 1 ? (row.status = 2) : (row.status = 1);
      });
  }
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getWarehouseLocationListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.perPage*1;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getWarehouseLocationListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.perPage*1;
      pagination.currentPage = val;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getWarehouseLocationListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.keyword = null;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
        status: 1,
        code: "",
        name: ""
      };
    } else {
      const res = await getWarehouseLocationShowApi({
        warehouseLocationId: row?.warehouseLocationId
      });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline.value = {
        title: "修改",
        warehouseLocationId: row?.warehouseLocationId ?? "",
        name: res?.result?.name ?? "",
        code: res?.result?.code ?? "",
        status: res?.result?.status ?? 1,
        warehouseId: res?.result?.warehouseId ?? 0,
        warehouseAreaId: res?.result?.warehouseAreaId ?? 0,
        number: res?.result?.number ?? "",
		row: res?.result?.row ?? null,
		storey: res?.result?.storey ?? null,
		column: res?.result?.column ?? null,
		long: res?.result?.long ?? null,
		width: res?.result?.width ?? null,
		height: res?.result?.height ?? null,
		volume: res?.result?.volume ?? null,
		capacity: res?.result?.capacity ?? null,
		payload: res?.result?.payload ?? null,
		remarks: res?.result?.remarks ?? null,
      };
    }
    addDialog({
      title: `${title}库位信息`,
      props: {
        formInline: formInline
      },
      width: "780px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了库位`, {
            type: "success"
          });
          done();
          onSearch();
        }
		curData.long = curData.long && curData.long > 0 ? curData.long.toFixed(2):null
		curData.width = curData.width && curData.width > 0 ? curData.width.toFixed(2):null
		curData.height = curData.height && curData.height > 0 ? curData.height.toFixed(2):null
		curData.volume = curData.volume && curData.volume > 0 ? curData.volume.toFixed(2):null
		curData.capacity = curData.capacity && curData.capacity > 0 ? curData.capacity.toFixed(2):null
		curData.payload = curData.payload && curData.payload > 0 ? curData.payload.toFixed(2):null
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createWarehouseLocationApi(nullObj(curData)).then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                chores();
              });
            } else {
              updateWarehouseLocationApi(nullObj(curData)).then((res) => {
				if(res.code !== 200) {
					message(res.msg ?? "操作失败,请联系管理员", {
					  type: "error"
					});
					return
				}
                chores();
              });
            }
          }
        });
      }
    });
  }
  function nullObj(obj) {
	   for (const key in obj) {
		  if (obj[key] === 0 || obj[key] === "" || obj[key] === null) {
			  delete obj[key];
		  }
	  }
	  return obj
  }
  onMounted(async () => {
    onSearch();
  });

  function handleDelete(row) {
    delWarehouseLocationApi({ goodsLocationId: row.goodsLocationId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete
  };
}
